package com.company.cloud.page.modules.mgr.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.cloud.art.modules.api.response.Artist;
import com.company.cloud.behavior.modules.api.response.BehaviorSearchListParam;
import com.company.cloud.behavior.modules.api.response.BehaviorSearchParam;
import com.company.cloud.behavior.modules.api.response.ThumbsUpSearchModel;
import com.company.cloud.common.asserts.ValidatorUtils;
import com.company.cloud.common.auth.annotation.Authc;
import com.company.cloud.common.auth.annotation.Login;
import com.company.cloud.common.bean.BaseClientResult;
import com.company.cloud.common.bean.BaseResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.constant.BaseConstant;
import com.company.cloud.common.constant.BaseReturnEnum;
import com.company.cloud.common.exception.BusinessException;
import com.company.cloud.common.utils.AuthContextUtils;
import com.company.cloud.common.utils.CheckUtils;
import com.company.cloud.company.modules.api.response.CompanyFull;
import com.company.cloud.page.modules.api.models.WechatMomentsModel;
import com.company.cloud.page.modules.app.controller.req.WechatMomentsQuery4PageParam;
import com.company.cloud.page.modules.base.entity.WechatMomentsInfo;
import com.company.cloud.page.modules.base.service.WechatMomentsInfoService;
import com.company.cloud.page.modules.cache.utils.MomentsConvertUtils;
import com.company.cloud.page.modules.mgr.controller.req.WechatMomentsCheckParam;
import com.company.cloud.user.modules.api.response.UserSimple;
import com.company.cloud.user.modules.api.service.UserRemoteService;
import com.company.common.server.constant.IRelBusiType;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.function.Function;

/**
 * 动态管理
 */
@Authc
@RestController
@RequestMapping("/mgr/cms/moments")
@Api(tags = "Page_MGR_动态管理")
public class WechatMomentsMgrController {

    @Autowired
    private WechatMomentsInfoService wechatMomentsInfoService;
    @Autowired
    private UserRemoteService userRemoteService;


    @PostMapping("/query")
    @ApiOperation(value = "查询动态", response = WechatMomentsModel.class)
    public BaseResult query(@RequestBody WechatMomentsQuery4PageParam params) {
        String video = null;
        String image = null;
        if (StrUtil.isNotEmpty(params.getFileType()) && "video".equals(params.getFileType())) {
            video = "video";
        }
        if (StrUtil.isNotEmpty(params.getFileType()) && "image".equals(params.getFileType())) {
            image = "image";
        }

        IPage<WechatMomentsInfo> page = wechatMomentsInfoService.page(new Page<WechatMomentsInfo>(params.getPage(), params.getRows()),
                new QueryWrapper<WechatMomentsInfo>()
                        .eq(CheckUtils.hasInt(params.getUserId()), "user_id", params.getUserId())
                        .eq(StrUtil.isNotEmpty(params.getCustType()), "cust_type", params.getCustType())
                        .eq(StrUtil.isNotEmpty(params.getCustCode()), "cust_code", params.getCustCode())
                        .eq("rows_state", BaseConstant.EnabledEnum.ENABLED.getCode())
                        .isNotNull(StrUtil.isNotEmpty(video), "videos")
                        .isNotNull(StrUtil.isNotEmpty(image), "imgs")
                        .orderByDesc("orders", "cdt")
        );

        if (page == null || CollUtil.isEmpty(page.getRecords())) {
            return BaseResult.ok();
        }

        Set<Integer> userIds = new HashSet<>();

        page.getRecords().forEach(item -> {
            userIds.add(item.getUserId());
        });

        BaseClientResult<Map<Integer, UserSimple>> userResult = userRemoteService.getUserMapByIds(userIds);
        Map<Integer, UserSimple> userMap = BaseClientResult.getResultData(userResult, new HashMap<>());


        IPage<WechatMomentsModel> data = page.convert(new Function<WechatMomentsInfo, WechatMomentsModel>() {
            @Override
            public WechatMomentsModel apply(WechatMomentsInfo entity) {
                return MomentsConvertUtils.getWechatMomentsModel(entity, userMap, null, null, null);
            }
        });
        return BaseResult.ok(data);
    }


    @GetMapping("/get")
    @ApiOperation(value = "获取动态", response = WechatMomentsModel.class)
    public BaseResult get(@RequestParam("id") Integer id) {


        WechatMomentsInfo entity = wechatMomentsInfoService.getById(id);
        if (entity == null || BaseConstant.EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }

        Set<Integer> userIds = new HashSet<>();
        userIds.add(entity.getUserId());


        BaseClientResult<Map<Integer, UserSimple>> userResult = userRemoteService.getUserMapByIds(userIds);
        Map<Integer, UserSimple> userMap = BaseClientResult.getResultData(userResult, new HashMap<>());

        WechatMomentsModel data = MomentsConvertUtils.getWechatMomentsModel(entity, userMap, null, null, null);
        return BaseResult.ok(data);
    }

    @PostMapping("/save")
    @ApiOperation(value = "修改动态排序", response = BaseResult.class)
    public BaseResult save(@RequestBody WechatMomentsInfo param) {
        WechatMomentsInfo entity = wechatMomentsInfoService.getById(param.getId());
        if (entity == null) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        entity.setOrders(param.getOrders());
        entity.setId(param.getId());
        wechatMomentsInfoService.updateById(entity);
        return BaseResult.ok(entity.getId());
    }

    @GetMapping("/del")
    @ApiOperation(value = "删除动态", response = BaseResult.class)
    public BaseResult del(@RequestParam("id") Integer id) {
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUserNoValidate();
        WechatMomentsInfo entity = wechatMomentsInfoService.getById(id);
        if (entity == null || BaseConstant.EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        entity.setRowsState(BaseConstant.EnabledEnum.DISABLED.getCode());
        entity.addEditParam(userInfo);
        wechatMomentsInfoService.updateById(entity);
        return BaseResult.ok();
    }


    @PostMapping("/check")
    @ApiOperation(value = "审核动态", response = BaseResult.class)
    public BaseResult check(@RequestBody WechatMomentsCheckParam params) {
        ValidatorUtils.validate(params);
        WechatMomentsInfo entity = wechatMomentsInfoService.getById(params.getId());
        if (entity == null || BaseConstant.EnabledEnum.DISABLED.getCode().equals(entity.getRowsState())) {
            throw new BusinessException(BaseReturnEnum.DATA_NOT_EXISTS);
        }
        LoginSimpleUserInfo userInfo = AuthContextUtils.getUser();
        entity.setState(params.getState());
        entity.addEditParam(userInfo);
        wechatMomentsInfoService.updateById(entity);

        return BaseResult.ok();
    }


}
